package com.shaomengjie.smjmvp.view.core;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.shaomengjie.smjmvp.widget.Dialog;

/**
 * Created by shaomengjie on 2017/5/19.
 */

public abstract class BaseFragment extends Fragment {
    private boolean isFirstLoad = true;
    private boolean isOnViewCreated = false;
    public static final String KEY_IS_BIND_VIEWPAGER = "key_is_bind_viewpager";
    private boolean isBindViewPager;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isFirstLoad = true;
        if (getArguments() != null)
            initializeArguments(getArguments());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(getFragmentLayoutId(), container, false);
    }
    protected abstract int getFragmentLayoutId();
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isOnViewCreated = true;
        initView(view);
        if (!isBindViewPager) {
            initData();
        }
    }
    protected void initData() {
    }
    protected abstract void initView(View v);

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isFirstLoad && isVisibleToUser && isOnViewCreated) {
            initData();
            isFirstLoad = false;
        }
    }

    /**
     * 初始化fragment的参数配置
     *
     * @param args 配置参数
     */
    protected void initializeArguments(Bundle args) {
        if (args != null) {
            isBindViewPager = args.getBoolean(KEY_IS_BIND_VIEWPAGER, false);
        }
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onStart() {
        super.onStart();
    }
    private Dialog dialog;
    public void showProgress(){
        if (dialog == null){
            dialog = new Dialog(getActivity());
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(false);
            dialog.show();
        }
    }
    public void closeProgress(){
        if (dialog!=null&&dialog.isShowing()){
            dialog.dismiss();
            dialog = null;
        }
    }
}
